(function(){

var role = require("./role");
var BusCon = require("../../core/bus/_con");
var UserCon = require("../../core/user/_con");
var GoodsCon = require("../../core/goods/_con");
var AchCon = require("../../core/ach/_con");
var db = require("../../core/db/index");
var config = require("../../core/_include/config");
var ResponObj = require("../_include/ResponObj");

module.exports = {
	prefix:"/user/buy",
	get:{
		"/makeach/:goods_id":function *(next){
			try{
				var user = role.getUser(this);
			}catch(e){
				var errorMsg = e;
			}
			var goods_id = this.params.goods_id;
			var goods;
			if (!user) {
				this.body = ResponObj("error",errorMsg);
			}else if (!(goods = GoodsCon.get(goods_id))) {
				this.body = ResponObj("error","找不到指定商品");
			}else {
				var bus = BusCon.get(goods.bus_id);
				if (bus) {
					try{
						var ach = user.makeAch(bus,goods_id);
						console.log("下单成功",ach._id);
						this.body = ResponObj("json",ach);
					}catch(e){
						this.body = ResponObj("error",e);
					}
				}else{
					this.body = ResponObj("error","找不到商品对应商家");
				}
			}

			yield next;
		},
		"/payach/:ach_id":function *(){
			var self = this;
			try{
				var user = role.getUser(this);
			}catch(e){
				var errorMsg = e;
			}
			var ach_id = this.params.ach_id;
			if (!user) {
				this.body = ResponObj("error",errorMsg);
			}else if (!AchCon.get(ach_id)) {
				this.body = ResponObj("error","找不到指定定单号");
			}else{
				try{
					user.payAch(ach_id,function(ach_id){
						self.body = ResponObj("json",{
							msg:"支付成功",
							ach_id:ach_id
						});
					});
				}catch(e){
					this.body = ResponObj("error",e);
				}
			}
		}
	},
	post:{
		"/":function *(next){
			this.body = this.request.body;
			yield next;
		}
	}
}

}());